import qs from 'qs'
export default {
    name: 'Usermg',
    components: {

    },
    data() {
        return {
            height: '600',
            currentPage: 1,
            pagesize: 5,
            total: 0,
            userData: [],
            multipleSelection: [],
            handlePassDialog: false,
            newPass: '',
            handleDialog: false,
            dialogButton: true,
            roleSetData: [],
            roleData: [],
            formLabelWidth: '120px',
            formLabels: [
                {
                    label: '用户名',
                    name: 'name'
                },
                {
                    label: '邮箱',
                    name:'email'
                },
                {
                    label:'手机号码',
                    name:'phone'   
                },
                {
                    label:'密码',
                    name:'pass'
                },
                {
                    label:"备注",
                    name:'remarks'
                }
            ],
            form:{
                name:'',
                email:'',
                phone:'',
                pass:'',
                remarks:'',
                uId:''
            }
        }
    },
    computed: {
        offset: function () {
            return (this.currentPage - 1) * this.pagesize;
        }
    },
    watch: {
        handleDialog:function(newVal,oldVal){
           if(oldVal){
               this.form = {
                   name:'',
                   email:'',
                   phone:'',
                   pass:'',
                   remarks:'',
                   uId:''
               }
               this.roleSetData = [];
               this.dialogButton = true;
           }
        },
        handlePassDialog: function (oldVal, newVal) {
            if (oldVal) {
                this.newPass = "";
            }
        }
    },
    created() {
        this.initRoleList();
        this.initUserList();
    },
    mounted() {

    },
    methods: {
        //获取所有的角色名称
        initRoleList(){
          this.$http.get('/roleInfoController/findRoleList')
           .then((res) => {
              if(res.status == 200){
                  this.roleData = res.rows;
              }
           }).catch((err) => { 
               console.log(err);
           });
        },
        //获取用户列表
        initUserList() {
            this.$http.post('/userController/findList?limit=' + this.pagesize + '&offset=' + this.offset)
                .then((res) => {
                    if (res.status == 200) {
                        this.userData = res.rows;
                        this.total = res.total;
                    }
                }).catch((err) => {
                    console.log(err);
            });
        },
        rowClick(row) {
            var array = [];
            for(var i=0;i < row.role.length;i++){
                array.push(row.role[i].rId);
            }
            this.roleSetData = array;
            this.form.name = row.name;
            this.form.email = row.email;
            this.form.phone = row.phone;
            this.form.remarks = row.remarks;
            this.form.uId = row.uId;
            this.handleDialog = true;
        },
        addUserBtn(){
           this.dialogButton = !this.dialogButton;
           this.handleDialog = true;
        },
        //新增用户
        subAdd() {
           var verifyForm = this.verifyForm();
           if(!verifyForm.status){
               this.$message.error(verifyForm.message);
               return;
           }
           var postData = {
               name:this.form.name,
               password:this.form.pass,
               email:this.form.email,
               phone:this.form.phone,
               remarks:this.form.remarks,
               roleIds:this.roleSetData.join(',')
           }

           //添加用户
           this.$http.post('/userController/addUserInfo',qs.stringify(postData))
            .then((res) => {
               if(res.status == 200){
                   this.$message({
                       type:'success',
                       message:res.message
                   });
                   this.initUserList();
                   this.handleDialog = false;
                   return;
               } else if(res.status ==500){
                this.$message.error(res.message);
               }
            }).catch((err) => {
               console.log(err);
            }) 
        },
        //修改用户
        subModify() {
            var verifyObj = this.verifyForm();
            if (!verifyObj.status) {
              this.$message.error(verifyObj.message);
              return;
            };
            var postData = {
              uId: this.form.uId,
              name: this.form.name,
              email: this.form.email,
              phone: this.form.phone,
              remarks: this.form.remarks,
              roleIds: this.roleSetData.join(',')
            };
            // 修改用户信息
            this.$http.post('/userController/updateUser', qs.stringify(postData))
              .then((res) => {
                if (res.status == 200) {
                  this.$message({
                    type: 'success',
                    message: res.message
                  });
                  this.initUserList();
                  this.handleDialog = false;
                  return;
                } else if(res.status == 500){
                    this.$message.error(res.message);
                }
              })
              .catch((res) => {
                console.log(res)
            })
        },
        activeFormatter(row, cloumn, cellValue, index) {
            return cellValue ? '已激活' : '未激活';
        },
        deleteRow(row, event) {
            this.$confirm('删除用户[' + row.name + '],确定继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.$http.post('/userController/delUserInfo', qs.stringify({ uId: row.uId }))
                    .then((res) => {
                        if (res.status == 200) {
                            this.$message({
                                type: 'success',
                                message: res.message
                            });
                            this.initUserList();
                            return;
                        }
                        this.$message.error(res.message);
                    }).catch((err) => {
                        console.log("res", err)
                    });
            }).catch(() => {
                this.$message({
                    type: 'type',
                    message: '已取消操作'
                })
            });
        },
        removeUserBtn() {
            if (this.multipleSelection.length < 1) {
                this.$message.error("请选择要删除的用户");
                return;
            }
            var postData = [];
            var nameArr = [];
            this.multipleSelection.forEach(function (val, idx) {
                postData.push(val.uId);
                nameArr.push(val.name);
            });
            var postData = postData.toString();
            var nameTxt = nameArr.toString();
            this.$confirm('删除[' + nameTxt + '],确定继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.get('/userController/delUserList?uIds=' + postData)
                    .then((res) => {
                        if (res.status == 200) {
                            this.$message({
                                type: 'success',
                                message: res.message
                            });
                            this.initUserList();
                            return;
                        }
                        this.$message.error(res.message);
                    }).catch((err) => {
                        console.log(err);
                });
            });
        },
        modifyPassButton() {
            if (this.multipleSelection.length == 0) {
                this.$message.error("请选择一个用户");
                return;
            } else if (this.multipleSelection.length > 1) {
                this.$message.error("一次只能修改一个用户");
            } else {
                this.handlePassDialog = true;
            }
        },
        modifyPass() {
            var passRule = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/; //密码正则
            if (!passRule.test(this.newPass)) {
                this.$message.error("密码由英文和数字组合，6-10位");
                return;
            }
            //修改密码
            this.$http.post('/userController/updatePasswordByUId?uId=' + this.multipleSelection[0].uId + '&password=' + this.newPass)
                .then((res) => {
                    if (res.status == 200) {
                        this.$message({
                            type: 'success',
                            message: res.message
                        });
                        this.initUserList();
                        this.handlePassDialog = false;
                        return;
                    } else if (res.status == 500) {
                        this.$message.error(res.message);
                    }
                }).catch((res) => {
                    console.log(res);
            });
        },
        activeClick(row, event) {
            var txt = row.active ? '锁定' : '激活';
            this.$confirm(txt + '用户[' + row.name + '],确定继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //激活和锁定用户
                this.$http.post('/userController/delUser', qs.stringify({ uId: row.uId }))
                    .then((res) => {
                        if (res.status == 200) {
                            this.$message({
                                type: 'success',
                                message: res.message
                            });
                            this.initUserList();
                            return;
                        }
                        this.$message.error(res.message);
                    }).catch((err) => {
                        this.$message({
                            type: 'text',
                            message: '已取消操作'
                        })
                    })
            })
        },
        verifyForm() {
            var returnData = {
                status: false,
                message: ''
            }
            var nameRule = /^[\u0391-\uFFE5\w]+$/; //用户名正则
            if (!nameRule.test(this.form.name)) {
                returnData.message = '用户名由中文、英文或下划线组成';
                return returnData;
            };

            var emailRule = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/; //邮箱正则
            if (!emailRule.test(this.form.email)) {
                returnData.message = '邮箱格式错误';
                return returnData;
            };

            var telRule = /^1[0-9]{10}$/; //电话正则
            if (!telRule.test(this.form.phone)) {
                returnData.message = '手机号码格式错误';
                return returnData;
            };

            var passRule = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/; //密码正则
            if (!this.dialogButton && !passRule.test(this.form.pass)) {
                returnData.message = '密码由英文和数字组合,6-10位';
                return returnData;
            };

            returnData.status = true;
            return returnData;
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleSizeChange(val) {
            this.pagesize = val;
            this.initUserList();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.initUserList();
        }
    },
}